package com.jinlejia.erp.ui.new_house.house;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.android.material.tabs.TabLayout;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.WrapContentLinearLayoutManager;
import com.jinlejia.erp.databinding.ActivityHouseTypeDetailsBinding;
import com.jinlejia.erp.ui.common.IntentLinkedHashMapWrapper;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.new_house.adapter.HouseTypeListAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.widget.FlashView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 户型详情Activity
 */
public class HouseTypeDetails extends AppCompatActivity {
    private ActivityHouseTypeDetailsBinding binding;
    private int picId;
    private ProgressDialog progressDialog;
    private HouseTypeListAdapter adapter;
    private LinkedHashMap<String, ArrayList<Map<String, Object>>> houseTypeMap = new LinkedHashMap<>();//处理后的户型列表数据
    private JSONObject housePicInfo;
    private IntentLinkedHashMapWrapper intentLinkedHashMapWrapper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_house_type_details);
        binding.setEvent(this);
        progressDialog = new ProgressDialog(this, "加载中...",false);
        progressDialog.show();
        picId = getIntent().getIntExtra("picId", 0);
        intentLinkedHashMapWrapper = (IntentLinkedHashMapWrapper) getIntent().getSerializableExtra("map");
        binding.idHouseAlbum.setPointsIsVisible(false);
        binding.idHouseAlbum.stopAutoPlay();
        binding.idHouseAlbum.setOnItemClickListener(new FlashView.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(HouseTypeDetails.this, HouseTypeActivity.class);
                intent.putExtra("position", position);
                intent.putExtra("json", housePicInfo.toJSONString());
                startActivity(intent);
            }
        });
        binding.idHomeRecyclerview.setHasFixedSize(true);
        binding.idHomeRecyclerview.setLayoutManager(new WrapContentLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        adapter = new HouseTypeListAdapter(new ArrayList<>());
        binding.idHomeRecyclerview.setAdapter(adapter);
        adapter.OnImagesListener(new HouseTypeListAdapter.OnImageListener() {
            @Override
            public void OnImageClick(int id) {
                Intent intent = new Intent(HouseTypeDetails.this, HouseTypeDetails.class);
                intent.putExtra("picId", id);
                intent.putExtra("map",new IntentLinkedHashMapWrapper(houseTypeMap));
                startActivity(intent);
            }
        });
        binding.idTableLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String title = String.valueOf(tab.getText());
                for (Map.Entry<String, ArrayList<Map<String, Object>>> entry : houseTypeMap.entrySet()) {
                    ArrayList<Map<String, Object>> value = entry.getValue();
                    if (title.equals(entry.getKey() + "(" + value.size() + ")")) {
                        adapter.setData(value);
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        getData();
    }

    private void getData() {
        OkHttpUtils.get().url(ApiConfig.HOUSEPICDETAIL.concat(String.valueOf(picId)))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(HouseTypeDetails.this, response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //region 楼盘基本信息解析绑定view
                            housePicInfo = data.getJSONObject("housePicInfo");
                            String picUrl = ApiConfig.MAGEHEADER_URL().concat(String.valueOf(housePicInfo.get("picUrl")));
                            List<String> list = new ArrayList<>();
                            list.add(picUrl);
                            binding.idHouseAlbum.setImagesUrl(list);
                            binding.idImgIndex.setText(1 + "/" + list.size());
                            binding.idHouseAlbum.setOnPageChangeListener(new FlashView.OnPageChangeListener() {
                                @Override
                                public void onPageChange(int position) {
                                    binding.idImgIndex.setText(position + 1 + "/" + list.size());
                                }
                            });
                            binding.tvHouseTypeName.setText(String.valueOf(housePicInfo.get("houseType")));
                            binding.tvHouseTypeMessage.setText(String.valueOf(housePicInfo.get("condition")));
                            if (!TextUtils.isEmpty(String.valueOf(housePicInfo.get("acreage")))) {
                                if (!TextUtils.isEmpty(String.valueOf(housePicInfo.get("saleState"))) && !String.valueOf(housePicInfo.get("saleState")).equals("null")) {
                                    if (Integer.parseInt(String.valueOf(housePicInfo.get("saleState"))) == 1) {
                                        binding.tvHouseTypeArea.setText("待售" + housePicInfo.get("acreage") + "㎡");
                                        binding.tvHouseTypeState.setText("待售");
                                        binding.tvHouseTypeState.setBackgroundColor(Color.parseColor("#FF8000"));
                                    } else {
                                        binding.tvHouseTypeArea.setText("在售" + housePicInfo.get("acreage") + "㎡");
                                        binding.tvHouseTypeState.setText("在售");
                                        binding.tvHouseTypeState.setBackgroundColor(Color.parseColor("#FAA700"));
                                    }
                                } else {
                                    binding.tvHouseTypeArea.setText(housePicInfo.get("acreage") + "㎡");
                                    binding.tvHouseTypeState.setVisibility(View.GONE);
                                }
                            }
                            if (!TextUtils.isEmpty(String.valueOf(housePicInfo.get("price"))) && !String.valueOf(housePicInfo.get("price")).equals("null")) {
                                if (String.valueOf(housePicInfo.get("price")).equals("0.0") || String.valueOf(housePicInfo.get("price")).equals("0")) {
                                    binding.tvHouseTypePrice.setText("价格待定");
                                } else {
                                    binding.tvHouseTypePrice.setText("约" + housePicInfo.get("price") + "万/套");
                                }
                            } else {
                                binding.tvHouseTypePrice.setText("价格待定");
                            }
                            binding.tvHouseTypeWuYe.setText(String.valueOf(housePicInfo.get("property")));
                            binding.tvHouseTypeProPerties.setText(String.valueOf(housePicInfo.get("houseName")));
                            //endregion

                            if (data.containsKey("otherPicList")) {
                                ArrayList<Map<String, Object>> housetypeList = (ArrayList<Map<String, Object>>) JSON.parseObject(String.valueOf(data.get("otherPicList")), new TypeReference<List<Map<String, Object>>>() {
                                });
                                houseTypeMap.clear();
                                binding.idTableLayout.removeAllTabs();
                                if (housetypeList.size() > 0) {
                                    for (Map<String, Object> map : housetypeList) {
                                        String roomType = String.valueOf(map.get("roomType"));
                                        if (houseTypeMap.containsKey(roomType)) {
                                            houseTypeMap.get(roomType).add(map);
                                        } else {
                                            ArrayList<Map<String, Object>> typeList = new ArrayList<>();
                                            typeList.add(map);
                                            houseTypeMap.put(roomType, typeList);
                                        }
                                    }

                                    for (Map.Entry<String, ArrayList<Map<String, Object>>> entry : houseTypeMap.entrySet()) {
                                        ArrayList<Map<String, Object>> value = entry.getValue();
                                        binding.idTableLayout.addTab(binding.idTableLayout.newTab().setText(entry.getKey() + "(" + value.size() + ")"));
                                    }
                                }
                            }

                        }
                    }
                });
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.id_back:
                finish();
                break;
            case R.id.tvMoreHouseType:
                Intent intent = new Intent(HouseTypeDetails.this, HouseTypeListActivity.class);
                EventBus.getDefault().postSticky(intentLinkedHashMapWrapper.getMap(), "TAG_HOUSETYPEONE_LIST");
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}